<?php

namespace App\Http\Controllers\Front;


use App\Model\Enterprise;
use App\Model\MaiBaoBill;
use App\Model\Common;
use App\Model\Spread;
use App\Model\SpreadUserShare;
use App\Model\UserDetail;
use Carbon\Carbon;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

/**
 * Class SpreadController
 * @package App\Http\Controllers\Front
 */
class SpreadController extends Controller
{
    private $user;

    public function __construct ()
    {
        $this->user = \Auth::user();
    }


    /**
     * @param Request $request
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        //todo 数据少
        $per_page = $request->query('per_page', 10);
//        $data = \DB::table("spread")
//            ->leftJoin("user_marketing", "spread.user_marketing_id", '=', 'user_marketing.id')
//            ->leftJoin("cards", "spread.card_id", "=", "cards.id")
//            ->select("spread.*", "user_marketing.title as user_marketing_title", "user_marketing.contents", "cards.head_picture", "cards.motto")
//            ->where("spread.status", 2)
//            ->where("spread.is_deleted", 0)
//            ->orderBy("spread.created_at", "desc");
//        $data = $data->paginate($per_page);


        $data = \DB::table("spread")
            ->where("status", "=", 2)
            ->where("is_deleted", "=", 0)
            ->orderBy("spread.created_at", "desc")
            ->paginate(10);
        $countData =  \DB::table("spread")
            ->where("status", "=", 2)
            ->where("is_deleted", "=", 0)
            ->get();
        //查找会员有card_id 的 并且查找出cards对应的数据
        $member_card_id = $countData->where("type", "=",0)->where("card_id","<>",0)->where("is_deleted", "=", 0)->pluck("card_id");
        $cards = (new \App\Model\Cards)->whereIn("id", array_unique($member_card_id->toArray()))->select ("id","head_picture", "motto")->get()->keyBy("id")->toArray();

        // 查找会员有marketing_id 的
        $member_marketing_id = $countData->where("type", "=",0)->where("user_marketing_id","<>",0)->pluck("user_marketing_id");

        $marketing = (new \App\Model\UserMarketing)->whereIn("id",array_unique($member_marketing_id->toArray()))->select("id", "title", "contents")->get()->keyBy("id")->toArray();

        // 企业查找
        $enterprise_id =  $countData->where("type", "=",1)
            ->where("card_id", "<>",0)
            ->where("is_deleted", "=", 0)
            ->pluck("user_id");

        $enterprise =  \DB::table("enterprise")->whereIn ("id",array_unique($enterprise_id->toArray()))->select("id", "name", "logo")->get()->keyBy("id")->toArray();
        return $this->renderJson([
            'data' => $data,
            "cards" => $cards,
            "marketing" => $marketing,
            "enterprise" => $enterprise
        ]);
    }

    /**
     * 获取企业详情
     * @param $id
     * @return \Illuminate\Http\Response
     */
    public function getEnterpriseById($id)
    {
        $enterprise =  Enterprise::where("id","=", $id)->first();

        return $this->renderJson ($enterprise);
    }

    /**
     * 查找单个
     * @param $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $data = \DB::table("spread")
            ->leftJoin("user_marketing", "spread.user_marketing_id", '=', 'user_marketing.id')
            ->leftJoin("cards", "spread.card_id", "=", "cards.id")
            ->select("spread.*", "user_marketing.title as user_marketing_title", "user_marketing.contents", "cards.head_picture", "cards.motto")
            ->where("spread.id", $id)
            ->first();
        return $this->renderJson($data);
    }

    /**
     * 添加
     * @param Request $request
     * @return \Illuminate\Http\Response
     * @throws \Exception
     */
    public function store(Request $request)
    {
        $this->validate($request, [
            'maibao_num' => 'required|numeric',
            'maibao_spend_num' => 'required|numeric',
            'cover' => 'required'
        ], [
            'maibao_num.required' => '脉宝总数不能为空！',
            'maibao_num.numeric' => '脉宝总数必须为数字',
            'maibao_spend_num.required' => '分享脉宝个数不能为空！',
            'maibao_spend_num.numeric' => '分享脉宝个数必须为数字',
            'cover.required' => '封面不能为空！'
        ]);
        $maibao_num = $request->input("maibao_num");
        $maibao_spend_num = $request->input("maibao_spend_num");
        $status = $request->input("status");
        if (!is_int($maibao_num / $maibao_spend_num)) {
            return $this->fail("每次分享脉宝个数分配不均！");
        }
        $user = $request->user();
        if ($user->maibao < $maibao_num) {
            return $this->fail("脉宝数量不够，请充值！");
        }
        if (!$province = isset($user->cards->province)) {
            $province = 0;
        }
        if ($user->maibao < $request->input("maibao")) {
            return $this->error("脉宝个数不够！,请充值");
        }
        $uuid = Common::uuid('spread');
        $data = $request->all();
        $data["code"] = $uuid;
        $data["user_id"] = (int)$user->id;
        $data["maibao_num_surplus"] = $status == 0 ? $maibao_num : 0;
        $data['province_id'] = $province;
        $spread = new Spread;

        \DB::beginTransaction();
        try {
            $result = $spread->create($data);
            if ($result["id"] > 0) {
                // 保存不用扣除脉宝
                if ($request->input('status') == 0) {
                    $con = "发布";
                    $this->saveMaiBaoBill($user->id, $request->input("title"), $maibao_num, $con);
                    // 设置redis
                    $redis = \Illuminate\Support\Facades\Redis::connection();
                    $redis->select(1);
                    $redis->set($uuid, $maibao_num);
                    // 新增扣除用户脉宝个数
                    $user->decrement('maibao', $maibao_num);
                }
                \DB::commit();
            }else{
                throw  new \Exception("系统错误！");
            }
            \DB::rollBack();
        } catch (\Exception $exception) {
            \Log::error($exception);
            \DB::rollBack();
            return $this->error('系统错误');
        }
        return $this->renderJson($result['id']);
    }

    /**
     * 修改
     * @param $id
     * @param Request $request
     * @return \Illuminate\Http\Response
     * @throws \Exception
     */
    public function update($id, Request $request)
    {
        $this->validate($request, [
            'maibao_num' => 'required|numeric',
            'maibao_spend_num' => 'required|numeric',
            'cover' => 'required'
        ], [
            'maibao_num.required' => '脉宝总数不能为空！',
            'maibao_num.numeric' => '脉宝总数必须为数字',
            'maibao_spend_num.required' => '分享脉宝个数不能为空！',
            'maibao_spend_num.numeric' => '分享脉宝个数必须为数字',
            'cover.required' => '封面不能为空！'
        ]);
        $maibao_num = $request->input("maibao_num");
        $maibao_spend_num = $request->input("maibao_spend_num");
        $status =  $request->input('status');
        if (!is_int($maibao_num / $maibao_spend_num)) {
            $this->fail("每次分享脉宝个数分配不均！");
        }
        $user = $request->user();

        if ($user->maibao < $maibao_num) {
            return $this->fail("脉宝个数不够！,请充值");
        }
        $data = $request->all();
        unset($data["remarks"]);
        unset($data["maibao_num_surplus"]);
        $data["remarks"] = null;
        // 如果是保存就清空maibao_num_surplus 如果是发布就保存剩余脉宝个数
        $data["maibao_num_surplus"] = $status == 4 ? 0 : $maibao_num;
        \DB::beginTransaction();
        try {
            $spread = Spread::where("id", $id)->first();
            $result = $spread->update($data);
            if ($result == false) {
                throw  new \Exception("添加失败！");
            }
            // 保存不用扣除脉宝
            if ( $status == 0) {
                // 添加脉宝记录
                $this->saveMaiBaoBill($user->id, $request->input("title"), $maibao_num,"发布");
                // 设置redis
                $redis = \Illuminate\Support\Facades\Redis::connection();
                $redis->select(1);
                $redis->set($spread->code, $maibao_num);
                // 减去会员脉宝个数
//                \Log::info ()
                $user->decrement('maibao', $maibao_num);
            }
            \DB::commit();
        } catch (\Exception $exception) {
            \DB::rollBack();
            \Log::error($exception);
            return $this->error('系统错误');
        }
        return $this->renderJson($result['id']);
    }


    /**
     * 删除
     * @param $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $spread = new  Spread();
        $spread = $spread->where("id", $id)->first();
        $spread->is_deleted = 1;
        $spread->save();
        if ($spread->status == 4){
            return $this->success();
        }
        // 删除redis
        $redis = \Illuminate\Support\Facades\Redis::connection();
        $redis->select(1);
        $redis->del($spread->code);
        return $this->success();
    }


    /**
     * 浏览量的添加
     * @param Request $request
     * @return \Illuminate\Http\Response
     */
    public function browseNum(Request $request)
    {
        $spread = (new \App\Model\Spread)->where("id", $request->input("id"))->first();
        $spread->increment('browse_num', 1);
        $spread->save();
        return $this->success();
    }

    /**
     * 发布管理列表
     * @return \Illuminate\Http\Response
     */
    public function getList(Request $request)
    {
        $user = $request->user();

        $data = \DB::table("spread")
            ->leftJoin("user_marketing", "spread.user_marketing_id", '=', 'user_marketing.id')
            ->leftJoin("cards", "spread.card_id", "=", "cards.id")
            ->select("spread.*", "user_marketing.title as user_marketing_title", "user_marketing.contents", "cards.head_picture", "cards.motto")
            ->where("spread.user_id", $user->id)
            ->where("spread.is_deleted", 0)
            ->orderBy("spread.created_at", "desc")
            ->paginate(10);

        return $this->renderJson($data);
    }

    /**
     * 添加分享
     * @param Request $request
     * @return \Illuminate\Http\Response
     * @throws \Exception
     */
    public function saveSpreadShare(Request $request)
    {
        $user = $request->user();
        // 分享内容id
        $spread_id = $request->input("spread_id");
        $spread = (new \App\Model\Spread)->where("id", $spread_id)->first();
        if (!$spread) {
            return $this->fail("广告不存在！");
        }
        $card = (new \App\Model\Cards)->where("user_id", $spread->user_id)->first();

        $user_detail = UserDetail::where("user_id", $spread->user_id)->first();

        $data = [
            'user_id' => $user->id,
            'spread_id' => $spread_id,
            'title' => $spread->title,
            'cover' => $spread->cover,
            'author_user_id' => $spread->user_id,
            'head_picture' => isset($card->head_picture) ? $card->head_picture : $user_detail->head_portrait,
            'user_name' => isset($card->user_name) ? $card->user_name : $user_detail->wechat_name
        ];
        $spreadUserShare = new SpreadUserShare;
        // 分享记录
        $share = $spreadUserShare
            ->where("user_id", $user->id)
            ->where("spread_id", $spread_id)
            ->whereDate('created_at','like',"%".date("Y-m-d", time())."%")
            ->first();
        $spread->increment('share_num', 1);
        // todo 当天获得了
        if ($share) {
            return $this->renderJson('', -1, '当天获得了');
        }
        $res = $spreadUserShare->create($data);
        //todo 自己分享不得脉宝
        if ($spread->user_id == $user->id) {
            return $this->renderJson('', -1, '自己分享不得脉宝');
        }
        if (!$res) {
            return $this->error("分享失败!");
        }
        $maibao_bill = new  MaiBaoBill();
        $maibao_bill_num = $maibao_bill
            ->where('user_id', $user->id)
            ->whereDate('created_at','like',"%".date("Y-m-d", time())."%")
            ->where("cate", '=', 1)
            ->where("type", '=', 1)
            ->where ("is_share", "=", 1)
            ->count();

        if($maibao_bill_num >=5){
            return $this->renderJson('', -1, '今天分享的脉宝次数已到5次！');
        }
        // todo 添加分享次数

        // 添加脉宝收益
        \DB::beginTransaction();
        try {
            // 更新脉宝剩余个数
            $redis = \Illuminate\Support\Facades\Redis::connection();
            $redis->select(1);
            if ($redis->exists($spread->code) == 0 || $spread->maibao_num_surplus == 0) {
                // todo 没有脉宝
                $redis->del($spread->code);
                // 广告下架广告
                $spread->status = 3;
                $spread->save();
                \DB::commit();
                throw new \Exception("没有脉宝1",-2);
            }
            $r = $redis->decrby($spread->code, $spread->maibao_spend_num);
            if ($r >= 0) {
                $spread->maibao_num_surplus = $redis->get($spread->code);
                if ($spread->save() == false) {

                    throw new \Exception("分享失败", -2, "");
                }
                // 添加分享记录
                $bill_id2 = \DB::table('maibao_bill')->insertGetId([
                    'user_id' => $user->id,
                    'type' => 1,
                    'is_share' => 1,
                    'title' => '分享全名推广' . $spread->title . "获得" . $spread->maibao_spend_num,
                    'amount' => $spread->maibao_spend_num,
                    'cate' => 1,
                    'created_at' => Carbon::now()
                ]);
                if (!$bill_id2) {
                    throw new \Exception("分享失败", -2, "");
                }
                $maibao_bill_extend_id = \DB::table('maibao_bill_extend')->insertGetId([
                    'type' => 1,
                    'user_id' => $user->id,
                    'bill_id' => $bill_id2,
                    'from_id' => $spread->user_id,
                    'created_at' => Carbon::now()
                ]);
                if (!$maibao_bill_extend_id) {
                    throw new \Exception("分享失败", -2, "");
                }
                $user->increment('maibao', $spread->maibao_spend_num);
                \DB::commit();
            } else {
                $redis->del($spread->code);
                // 广告下架广告
                $spread->status = 3;
                $spread->save();
                throw new \Exception("分享成功！，广告下架", 0, "");
            }

        } catch (\Exception $e) {
            \DB::rollBack();
            if ($e->getCode() == 0) {
                \DB::commit();
                return $this->renderJson($e);
            }
            return $this->renderJson("", $e->getCode(), $e->getMessage());
        }
        return $this->renderJson('', 0, '分享成功！');
    }

    /**
     * 分享记录
     * @return \Illuminate\Http\Response
     */
    public function spreadShareList(Request $request)
    {
        $user = $request->user();
        $spreadUserShare = new SpreadUserShare;
        $data = $spreadUserShare
            ->where("user_id", $user->id)
            ->orderBy("created_at", "desc")
            ->paginate(10);
        return $this->renderJson($data);
    }

    /**
     * 今天获得脉宝多少次了
     * @param Request $request
     * @return \Illuminate\Http\Response
     */
    public function spreadShareNum(Request $request)
    {

        $user = $request->user();
        $maibao_bill = new  MaiBaoBill();
        $maibao_bill_num = $maibao_bill
            ->where('user_id', $user->id)
            ->where("cate", '=', 1)
            ->where("type", '=', 1)
            ->where ("is_share", "=", 1)
            ->whereDate('created_at','like',"%".date("Y-m-d", time())."%")
            ->count();

        return $this->renderJson(['spread_share_num' => $maibao_bill_num]);
    }

    //添加脉宝记录
    public function saveMaiBaoBill($user_id, $title, $maibao_num, $con)
    {
        $bill_id = \DB::table('maibao_bill')->insertGetId([
            "user_id" => $user_id,
            "type" => -1,
            'title' => $con.'全民推广' . $title,
            'amount' => $maibao_num,
            'cate' => 1,
            'created_at' => Carbon::now()
        ]);
        \DB::table('maibao_bill_extend')->insert([
            'type' => 1,
            'user_Id' => $user_id,
            'bill_id' => $bill_id,
            'created_at' => Carbon::now()
        ]);

    }
}
